package info.batcloud.fanli.api.controller;

import info.batcloud.fanli.core.dto.FreeChargeActivityDTO;
import info.batcloud.fanli.core.domain.BusinessResponse;
import info.batcloud.fanli.core.helper.SecurityHelper;
import info.batcloud.fanli.core.service.FreeChargeActivityService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/free-charge-activity")
public class FreeChargeActivityController {

    @Inject
    private FreeChargeActivityService freeChargeActivityService;

    @GetMapping("/check/draw")
    @PreAuthorize("hasRole('USER')")
    public Object checkDraw(CheckDrawForm form) {
        long userId = SecurityHelper.loginUserId();
        FreeChargeActivityService.CheckDrawResult checkResult = freeChargeActivityService.checkUserDraw(userId, form.getItemId(), form.getFreeChargeActivityId());
        FreeChargeActivityDTO activity = freeChargeActivityService.findById(form.getFreeChargeActivityId());
        Map<String, Object> model = new HashMap<>();
        model.put("success", checkResult.isSuccess());
        model.put("msg", checkResult.getMsg());
        model.put("errMsg", checkResult.getErrMsg());
        model.put("activityName", activity.getName());
        model.put("activityHelpUrl", activity.getHelpUrl());
        return BusinessResponse.ok(model);
    }

    @PostMapping("/check/order")
    @PreAuthorize("hasRole('USER')")
    public Object checkDrawOrder(CheckDrawForm form) {
        long userId = SecurityHelper.loginUserId();
        FreeChargeActivityService.CheckDrawResult checkResult = freeChargeActivityService.checkUserDrawToOrder(userId, form.getItemId(), form.getFreeChargeActivityId());
        return BusinessResponse.ok(checkResult);
    }

    public static class CheckDrawForm {
        private Long freeChargeActivityId;
        private Long itemId;

        public Long getFreeChargeActivityId() {
            return freeChargeActivityId;
        }

        public void setFreeChargeActivityId(Long freeChargeActivityId) {
            this.freeChargeActivityId = freeChargeActivityId;
        }

        public Long getItemId() {
            return itemId;
        }

        public void setItemId(Long itemId) {
            this.itemId = itemId;
        }
    }

}
